package com.geeguo.ebuilder.operation.controller.system.role;

import com.alibaba.fastjson.JSON;
import com.geeguo.ebuilder.core.common.action.ActionResult;
import com.geeguo.ebuilder.core.common.model.vo.PageListVO;
import com.geeguo.ebuilder.core.common.utils.key.UUIDCheckUtils;
import com.geeguo.ebuilder.core.common.utils.key.UUIDGenerator;
import com.geeguo.ebuilder.core.security.annotation.RequiresLogin;
import com.geeguo.ebuilder.core.security.annotation.RequiresPermissions;
import com.geeguo.ebuilder.operation.base.core.constants.MessageConstants;
import com.geeguo.ebuilder.operation.base.core.dictionary.ClientTypeEnum;
import com.geeguo.ebuilder.operation.base.core.dictionary.LogTypeEnum;
import com.geeguo.ebuilder.operation.base.security.model.LoginUser;
import com.geeguo.ebuilder.operation.base.security.utils.AuthUtils;
import com.geeguo.ebuilder.operation.base.log.annotation.Log;
import com.geeguo.ebuilder.operation.business.system.role.model.*;
import com.geeguo.ebuilder.operation.business.system.role.service.RoleService;
import com.geeguo.ebuilder.operation.business.system.rolewebmodule.model.RoleWebModuleEntity;
import com.geeguo.ebuilder.operation.business.system.rolewebmodule.service.RoleWebModuleService;
import com.geeguo.ebuilder.operation.business.system.webmodule.model.WebModuleVO;
import com.geeguo.ebuilder.operation.business.system.webmodule.service.WebModuleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Tag(name = "角色管理")
@RestController
public class RoleController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private WebModuleService webModuleService;
    @Autowired
    private RoleWebModuleService roleWebModuleService;

    @Operation(summary = "分页查询")
    @PostMapping("/system/role/list")
    @RequiresPermissions("System:Role")
    public ActionResult<PageListVO<RoleVO>> list(@RequestBody RoleQuery query) {
        return ActionResult.page(roleService.list(query));
    }

    @Operation(summary = "保存角色")
    @PostMapping("/system/role/save")
    @RequiresPermissions("System:Role")
    public ActionResult<Boolean> save(@Validated @RequestBody RoleCreateDTO dto) {
        if (StringUtils.isNotEmpty(dto.getCode())) {
            RoleVO role = roleService.getByCode(dto.getCode());
            if (role != null) {
                return ActionResult.fail("角色编码已经存在");
            }
        }
        LoginUser currentUser = AuthUtils.getLoginUser();
        RoleEntity role = RoleConverter.INSTANCE.convert2Entity(dto);
        role.setId(UUIDGenerator.getId());
        role.setCreateTime(new Date());
        role.setCreateUser(currentUser.getUserId());
        if (roleService.save(role)) {
            return ActionResult.success();
        }
        return ActionResult.fail();
    }

    @Operation(summary = "根据ID获取信息")
    @GetMapping("/system/role/get/{id}")
    @RequiresPermissions("System:Role")
    public ActionResult<RoleVO> get(@PathVariable("id") String id) {
        if (UUIDCheckUtils.check(id)) {
            RoleVO role = roleService.get(id);
            if (role != null) {
                return ActionResult.success(role);
            }
            return ActionResult.fail(MessageConstants.FAIL_DATA_NOT_EXIST);
        }
        return ActionResult.fail(MessageConstants.FAIL_REQUEST_DATA_ERROR);
    }

    @Operation(summary = "更新角色")
    @PostMapping("/system/role/update")
    @RequiresPermissions("System:Role")
    public ActionResult<Boolean> update(@Validated @RequestBody RoleUpdateDTO dto) {
        LoginUser currentUser = AuthUtils.getLoginUser();
        RoleVO old = roleService.get(dto.getId());
        if (old != null) {
            RoleEntity role = RoleConverter.INSTANCE.convert2Entity(dto);
            role.setModifyTime(new Date());
            role.setModifyUser(currentUser.getUserId());
            if (roleService.update(role, RoleConverter.INSTANCE.convert2Entity(old))) {
                return ActionResult.success();
            }
        }
        return ActionResult.fail();
    }

    @Operation(summary = "删除角色")
    @PostMapping("/system/role/remove")
    @RequiresPermissions("System:Role")
    @Log(title = "删除角色", logType = LogTypeEnum.DELETE, clientType = ClientTypeEnum.Web)
    public ActionResult<Boolean> remove(@RequestParam("id") String id) {
        if (UUIDCheckUtils.check(id)) {
            if (roleService.isUsed(id)) {
                return ActionResult.fail(MessageConstants.DATA_USED);
            }
            if (roleService.remove(id)) {
                return ActionResult.success();
            }
        }
        return ActionResult.fail();
    }

    @Operation(summary = "查询Web菜单")
    @GetMapping("/system/role/listWebModule/{id}")
    @RequiresPermissions("System:Role")
    public ActionResult<RoleWebModuleVO> listWebMenu(@PathVariable("id") String id) {
        RoleWebModuleVO roleWebModule = new RoleWebModuleVO();
        List<WebModuleVO> list = webModuleService.listAllTree();
        roleWebModule.setWebModules(list);
        roleWebModule.setCheckedWebModuleIds(roleWebModuleService.listModuleIdByRole(id));
        return ActionResult.success(roleWebModule);
    }

    @Operation(summary = "更新菜单")
    @PostMapping("/system/role/updateModule")
    @RequiresPermissions("System:Role")
    public ActionResult<Boolean> updateModule(@RequestBody Map<String, String> body) {
        String id = body.get("id");
        String webModuleIds = body.get("webModuleIds");
        if (UUIDCheckUtils.check(id)) {
            List<String> moduleIds = JSON.parseArray(webModuleIds, String.class);
            List<String> existedModuleIds = roleWebModuleService.listModuleIdByRole(id);
            Collection<String> addModuleIds = CollectionUtils.subtract(moduleIds, existedModuleIds);
            Collection<String> deleteModuleIds = CollectionUtils.subtract(existedModuleIds, moduleIds);
            if (CollectionUtils.isEmpty(addModuleIds) && CollectionUtils.isEmpty(deleteModuleIds)) {
                return ActionResult.success(true);
            }
            List<RoleWebModuleEntity> entities = new ArrayList<>();
            if (!CollectionUtils.isEmpty(addModuleIds)) {
                LoginUser currentUser = AuthUtils.getLoginUser();
                RoleWebModuleEntity entity = null;
                for (String moduleId : addModuleIds) {
                    entity = new RoleWebModuleEntity();
                    entity.setId(UUIDGenerator.getId());
                    entity.setRoleId(id);
                    entity.setWebModuleId(moduleId);
                    entity.setCreateTime(new Date());
                    entity.setCreateUser(currentUser.getUserId());
                    entities.add(entity);
                }
            }
            if (roleWebModuleService.updateModule(id, entities, new ArrayList<>(deleteModuleIds))) {
                return ActionResult.success();
            }
        }
        return ActionResult.fail();
    }

    @Operation(summary = "查询角色列表，通用方法，登录即可访问")
    @GetMapping("/system/role/listAll")
    @RequiresLogin
    public ActionResult<List<RoleVO>> listAll() {
        return ActionResult.success(roleService.listAll());
    }
}